package com.patchmanage.back.controller;


import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.patchmanage.back.annotation.OperLog;
import com.patchmanage.back.entity.Patch;
import com.patchmanage.back.entity.PatchGroup;
import com.patchmanage.back.exception.SystemException;
import com.patchmanage.back.result.CodeMsg;
import com.patchmanage.back.result.Result;
import com.patchmanage.back.service.IPatchGroupService;
import com.patchmanage.back.service.IPatchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  补丁组
 * </p>
 *
 * @author huizhao
 * @since 2021-03-20
 */
@Api(value = " 补丁组 controller", tags = {"补丁组 Api"})
@RestController
@RequestMapping("/back/patchgroup")
public class PatchGroupController {
    @Autowired
    public IPatchGroupService patchGroupService;

    @Autowired
    public IPatchService patchService;

    /**
     * 获取补丁组列表
     * @param dict
     * @return
     */
    @ApiOperation(value = "获取补丁组列表接口", notes = "获取补丁组列表接口")
    @RequestMapping(value = "list", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pId", value = "pId", required = false, dataType = "Integer", paramType = "body")
    })
    public Result<JSONArray> list(@RequestBody Dict dict) {

        Integer pId = dict.getInt("pId") == null ? 0 : dict.getInt("pId");

        QueryWrapper<PatchGroup> queryWrapper = new QueryWrapper<PatchGroup>();
        List<PatchGroup> groupList = patchGroupService.list(queryWrapper);
        return Result.success(treeMenuList(JSONUtil.parseArray(groupList),pId));
    }

    private JSONArray treeMenuList(JSONArray menuList, int parentId) {
        JSONArray childMenu = new JSONArray();
        for (Object object : menuList) {
            JSONObject jsonMenu = JSONUtil.parseObj(object);
            int menuId = jsonMenu.getInt("id");
            int pid = jsonMenu.getInt("pId");
            if (parentId == pid) {
                JSONArray c_node = treeMenuList(menuList, menuId);
                jsonMenu.putOnce("childNode", c_node);
                childMenu.add(jsonMenu);
            }
        }
        return childMenu;
    }

    @ApiOperation(value = "新增补丁组列表接口", notes = "新增补丁组列表接口")
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pId", value = "pId", required = false, dataType = "Integer", paramType = "body"),
            @ApiImplicitParam(name = "name", value = "name", required = false, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "sort", value = "sort", required = false, dataType = "Integer", paramType = "body")
    })
    @OperLog(operModul="补丁组",operDesc="新增补丁组列表")
    public Result<Boolean> saveOrUpdate(@RequestBody PatchGroup patchGroup){

        /** 修改 **/
        if(patchGroup.getId() != null && StrUtil.isNotBlank(patchGroup.getName())){
            // 修改所有的补丁设置
            Patch patch = new Patch();
            patch.setPatchGroupName(patchGroup.getName());

            UpdateWrapper<Patch> patchUpdateWrapper = new UpdateWrapper<>();
            patchUpdateWrapper.eq("patch_group_id", patchGroup.getId());
            patchService.update(patch, patchUpdateWrapper);

        }
        return Result.success(patchGroupService.saveOrUpdate(patchGroup));
    }

    @ApiOperation(value = "删除补丁组接口", notes = "删除补丁组接口")
    @RequestMapping(value = "removeByIds", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true, dataType = "String", paramType = "body")
    })
    @OperLog(operModul="补丁组",operDesc="删除补丁组")
    public Result<Boolean> removeByIds(@RequestBody Dict dict){
        String id = dict.getStr("ids");
        String[] ids = id.split(",");

        /** 判断有没有绑定补丁 **/
        for(String idStr : ids){
            QueryWrapper<Patch>  queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("patch_group_id", Integer.valueOf(idStr));
            Integer count = patchService.count(queryWrapper);
            if(count > 0){
                throw new SystemException(CodeMsg.PATCH_EXIST_ERROR);
            }
        }

        return Result.success(patchGroupService.removeByIds(Arrays.asList(ids)));
    }

    @ApiOperation(value = "获取补丁组接口", notes = "获取补丁组接口")
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "body")
    })
    public Result<PatchGroup> getById(@RequestBody Dict dict){
        String id = dict.getStr("id");
        return Result.success(patchGroupService.getById(id));
    }
}
